package com.xing.controller;


import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.xing.common.dto.BrowseDto;
import com.xing.model.Blog;
import com.xing.service.BlogService;
import com.xing.service.CollectService;
import com.xing.util.IPUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 * 收藏控制器
 * @author 柠檬有点甜
 * @since 2021-10-11
 */
@RestController
@RequestMapping("/collect")
public class CollectController {
    @Autowired
    CollectService collectService;

    @Autowired
    BlogService blogService;



    /**
     * 查询该用户是否已经收藏过该文章了
     * @param blogId
     * @param userId
     * @return
     */
    @GetMapping("/userCollectState")
    public boolean userCollectState(int blogId,int userId){
        return  collectService.userCollectState(String.valueOf(blogId),String.valueOf(userId));
    }

    /**
     * 文章收藏与取消收藏
     * @param blogId 文章id
     * @param userId 用户id
     * @param state 是否收藏
     */
    @GetMapping("/setCollect")
    public void setCollect(int blogId,int userId,boolean state){
        String aid = String.valueOf(blogId);
        String uid = String.valueOf(userId);
        //如果是true未收藏则需要收藏
        if (state){
//            System.out.println("收藏");
            collectService.collectBlog(aid,uid);
        }
        else
        {
            collectService.unCollectBlog(aid,uid);
        }
    }

    /**
     * 删除redis收藏数量
     * 定时保存数据库
     */
    @Scheduled(cron = "*/120 * * * * ?") //每120秒更新一次
    public void detectCollectRedis(){
        List<BrowseDto> collectCountFromRedis = collectService.getCollectCountFromRedis();
        if (CollectionUtils.isNotEmpty(collectCountFromRedis)){//不为空才更新
            blogService.addCollectCount(collectCountFromRedis);
        }
    }


}

